package com.iwhalecloud.bss.kite.cucc.service.util;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @Description 地图辅助查询工具类
 * @Author deng.gang
 * @Date 2022/2/18 11:03 上午
 */
public class MapAidUtil {

    private static final ZLogger logger = ZLoggerFactory.getLogger(MapAidUtil.class, KeyConsts.LOG_MODULE);

    private static final String ADD = "/add/";

    /**
     * 加密
     * 算法：AES 模式：ECB 补码方式：PKCS5Padding
     * @param sSrc
     * @param sKey
     * @return
     */
    public static String encrypt(String sSrc, String sKey) {
        String result = null;
        try {
            Base64 base64 = new Base64();
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
            result = base64.encodeToString(encrypted);
            result = result.replaceAll("\\s*", "");
            result = result.replaceAll("\\+", ADD);
        }
        catch (Exception e) {
            logger.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, "Failed to encrypt, " + e.getMessage());
        }
        return result;
    }

    /**
     * 解密
     * @param sSrc
     * @param sKey
     * @return
     */
    public static String decrypt(String sSrc, String sKey) {
        String result = null;
        try {
            sSrc = sSrc.replaceAll("\\s*", "");
            sSrc = sSrc.replaceAll(ADD,"+");
            Base64 base64 = new Base64();
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = base64.decode(sSrc); // 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            result = new String(original, StandardCharsets.UTF_8);
        }
        catch (Exception ex) {
            logger.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), ex, "Failed to decrypt, " + ex.getMessage());
        }
        return result;
    }
}
